;
(function (window, $) {
  var App = {
    init: function () {
      var me = this;
      me.render();
      me.bind();
    },
    const: {
      chartMethod: {
        totalFreq: 'GetFreqCount',
        upFlow: 'GetUpLink',
        downFlow: 'GetDownLink',
        totalFlow: 'GetLink'
      },
      voronoiMethod: {
        totalFreq: 'GetFreqVoronoi',
        upFlow: 'GetUpLinkVoronoi',
        downFlow: 'GetDownLinkVoronoi',
        totalFlow: 'GetLinkVoronoi'
      },
      voronoiLegend: {
        totalFreq: 'allFreqValue',
        upFlow: 'allUpLinkValue',
        downFlow: 'allDownLinkValue',
        totalFlow: 'allLinkValue'
      }
    },
    data: {
      fakeDraw: false
    },
    render: function () {
      var me = this;
      me.window = $(window);
      me.tabbox = $('#tab_box');
      me.city = $('#cityPicker');
      me.date = $('#datePicker');
      me.queryBtn = $('#query');
      me.form = $('#form');
      me.totalfreqChartDom = $('#totalfreqChart');
      me.upChartDom = $('#upChart');
      me.downChartDom = $('#downChart');
      me.totalflowChartDom = $('#totalflowChart');
      me.totalfreqChart = false;
      me.upflowChart = false;
      me.downflowChart = false;
      me.totalflowChart = false;
      me.totalfreqCount = $('#totalfreqCount');
      me.upflowCount = $('#upflowCount');
      me.downflowCount = $('#downflowCount');
      me.flowCount = $('#flowCount');
      me.dateSelect = $('#datePicker');

      me.cityPicker = me.initCity();
      me.datePicker = me.initDate();
    },
    bind: function () {
      var me = this
      me.tabbox.on('click', $.proxy(me['_do_switch_tab'], this));
      me.queryBtn.on('click', $.proxy(me['_do_query'], this));
      me.window.on('resize', $.proxy(me['_do_resize'], this));
    },
    _do_switch_tab: function (e) {
      var me = this;
      var $target = $(e.target);
      var contentId = $target.data('content');
      window.Map.data.contentId = contentId;

      if (contentId) {
        var $content = $('#' + contentId);
        var lmap = window.Map.map;
        $target.addClass('active');
        $target.siblings('.top-bar__tab').removeClass('active');
        $content.addClass('active');
        $content.siblings('.right-content').removeClass('active');

        me.setWidget();
        me.removeVoronoiLayer();
        if (contentId !== 'totalFreq') {
          window.Map.layer.canvas.delegate(window).removeFrom(lmap);
        }
      }
    },
    removeVoronoiLayer: function () {
      var map = window.Map;
      var lmap = map.map;
      var voronoiLayer = map.layer.voronoiLayer;
      if (lmap.hasLayer(voronoiLayer)) {
        voronoiLayer.removeFrom(lmap);
        // lmap.setView({
        //   lng: 107.90,
        //   lat: 35.84
        // }, 4);
      }
    },
    setWidget: function () {
      var widget = window.Map.widget;
      var widgetKeys = Object.keys(widget);

      for (o of widgetKeys) {
        widget[o].remove();
      }
      
      window.Map.cellWidget.remove();
    },
    _do_query: function (e) {
      var me = this;
      var query = me.form.serialize();
      var queryObj = me.form.serializeJSON();
      var city = queryObj.city;
      var contentId = N.Dom.getActiveBtn('.top-bar__tab');
      // var zoom = window.Map.map.getZoom();

      window.Map.data.contentId = contentId;
      $('#' + contentId).css({
        height: 'calc(100% - 192px)',
        width: '100%'
      });
      if (!city || !queryObj.date) {
        alert('请选择地市和日期');
        return;
      }

      if (typeof jsObj !== 'undefined') {
        // jsObj为C#生成的js对象
        var usChartData = jsObj[me.const.chartMethod[contentId]](query);
        var usVoronoiData = jsObj[me.const.voronoiMethod[contentId]](query);
        
        var chartData;
        var voronoiData;

        if (contentId === 'totalFreq') {
          var usCellList = jsObj.GetAreaFreqCount(query);
          var cellList;

          try {
            cellList = JSON.parse(usCellList);
          } catch (err) {
            alert(err);
            return;
          }

          if (cellList) {
            window.Map.setCellData(cellList, city);
          }
        }

        try {
          chartData = JSON.parse(usChartData);
        } catch (err) {
          alert(err);
          return;
        }

        try {
          voronoiData = JSON.parse(usVoronoiData);
        } catch (err) {
          alert(err);
          return;
        }

        if (chartData) {
          me[contentId + 'Chart'](chartData);
        }

        if (voronoiData) {
        // 执行两次，解决多边形绘制个数不对的问题
          if (!me.data.fakeDraw) {
            window.Map.setVoronoiData(window.gFakeStationList, contentId, city, 'fake');
            me.data.fakeDraw = true
          }
          window.Map.setVoronoiData(voronoiData, contentId, city);
        }
      } else {
        var stationList = window.gStationList;
        var fakeStationList = window.gFakeStationList
        var cellList = window.gCellList;

        // 执行两次，解决多边形绘制个数不对的问题
        if (!me.data.fakeDraw) {
          window.Map.setVoronoiData(fakeStationList, contentId, city, 'fake');
          me.data.fakeDraw = true
        }
        window.Map.setVoronoiData(stationList, contentId, city);

        if (contentId === 'totalFreq') {
          window.Map.setCellData(cellList, city);
        } else {
          window.Map.setCellNoData();
        }
      }
    },
    _do_resize: function (e) {
      var me = this;
      me.totalfreqChart ? me.totalfreqChart.resize() : '';
      me.upflowChart ? me.upflowChart.resize() : '';
      me.downflowChart ? me.downflowChart.resize() : '';
      me.totalflowChart ? me.totalflowChart.resize() : '';
    },
    totalFreqChart: function (data) {
      var me = this;
      if (!me.totalfreqChart) {
        me.totalfreqChart = echarts.init(me.totalfreqChartDom[0]);
      }
      var option = {
        color: ['#b1e1b1', '#8cc88c', '#6caf6c', '#58a158', '#439243', '#307a2f', '#2f7a51'],
        title: {
          text: '',
        },
        tooltip: {
          trigger: 'item',
          formatter: "{a} <br/>{b} : {c} ({d}%)"
        },
        legend: {
          type: 'scroll',
          orient: 'vertical',
          right: 10,
          top: 20,
          bottom: 20,
          data: data.legendData
        },
        series: [{
          name: '总频点数',
          type: 'pie',
          radius: '55%',
          center: ['40%', '50%'],
          label: {
            show: false
          },
          data: data.seriesData
        }]
      };

      me.totalfreqChart.setOption(option);
      me.totalfreqCount.text(data.total);
    },
    upFlowChart: function (data) {
      var me = this;
      if (!me.upflowChart) {
        me.upflowChart = echarts.init(me.upChartDom[0]);
      }
      var option = {
        color: ['#b1e1b1', '#8cc88c', '#6caf6c', '#58a158', '#439243', '#307a2f', '#2f7a51'],
        title: {
          text: '',
        },
        tooltip: {
          trigger: 'item',
          formatter: "{a} <br/>{b} : {c} ({d}%)"
        },
        legend: {
          type: 'scroll',
          orient: 'vertical',
          right: 10,
          top: 20,
          bottom: 20,
          data: data.legendData
        },
        series: [{
          name: '上行流量分布',
          type: 'pie',
          radius: '55%',
          center: ['40%', '50%'],
          label: {
            show: false
          },
          data: data.seriesData
        }]
      };
      me.upflowChart.setOption(option);
      me.upflowCount.text(data.total);
    },
    downFlowChart: function (data) {
      var me = this;
      if (!me.downflowChart) {
        me.downflowChart = echarts.init(me.downChartDom[0]);
      }
      var option = {
        color: ['#b1e1b1', '#8cc88c', '#6caf6c', '#58a158', '#439243', '#307a2f', '#2f7a51'],
        title: {
          text: '',
        },
        tooltip: {
          trigger: 'item',
          formatter: "{a} <br/>{b} : {c} ({d}%)"
        },
        legend: {
          type: 'scroll',
          orient: 'vertical',
          right: 10,
          top: 20,
          bottom: 20,
          data: data.legendData
        },
        series: [{
          name: '下行流量分布',
          type: 'pie',
          radius: '55%',
          center: ['40%', '50%'],
          label: {
            show: false
          },
          data: data.seriesData
        }]
      };
      me.downflowChart.setOption(option);
      me.downflowCount.text(data.total);
    },
    totalFlowChart: function (data) {
      var me = this;
      if (!me.totalflowChart) {
        me.totalflowChart = echarts.init(me.totalflowChartDom[0]);
      }
      var option = {
        color: ['#b1e1b1', '#8cc88c', '#6caf6c', '#58a158', '#439243', '#307a2f', '#2f7a51'],
        title: {
          text: '',
        },
        tooltip: {
          trigger: 'item',
          formatter: "{a} <br/>{b} : {c} ({d}%)"
        },
        legend: {
          type: 'scroll',
          orient: 'vertical',
          right: 10,
          top: 20,
          bottom: 20,
          data: data.legendData
        },
        series: [{
          name: '总流量分布',
          type: 'pie',
          radius: '55%',
          center: ['40%', '50%'],
          label: {
            show: false
          },
          data: data.seriesData
        }]
      };
      me.totalflowChart.setOption(option);
      me.flowCount.text(data.total);
    },
    initCity: function () {
      var me = this
      return me.city.citypicker()
    },
    setDateOptions: function(sMonthList) {
      var me = this;
      var dateSelect = me.dateSelect;
      var dom = '';
      sMonthList.forEach(function(item) {
        var date_month = item.date_month
        dom += '<option value="' + date_month + '">' + date_month + '</option>';
      });

      dateSelect.append(dom);
      dateSelect.removeAttr('disabled');
    },
    initDate: function () {
      var me = this;
      if (typeof jsObj !== 'undefined') {
        var usMonthList = jsObj._tablesName;
        var sMonthList;
        try {
          sMonthList = JSON.parse(usMonthList);
        } catch(err) {
          alert(usMonthList);
          alert(err);
          return;
        }

        me.setDateOptions(sMonthList);
      } else {
        me.setDateOptions(window.gDateList);
      }

      // return me.date.datetimepicker({
      //   format: "YYYY-MM",
      //   locale: 'zh-cn'
      // })
    },
  }

  App.init()

  window.App = App
})(window, jQuery)